package com.codeyang.controller;

import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 描述: 文件上传
 *
 * @author CodeYang_Site
 * @version 2021/5/24 20:13
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("admin/file")
public class FileController {

    /**
     * FastDfs文件上传客户端
     */
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 保证请求地址发送改变,但是上传的地址还是指向配置的fastdfs
     */
    @Value("${resources.url}")
    private String serverHost;

    @ApiOperation("文件上传")
    @PostMapping("upload/element")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        String fullPath = "";
        try {
            // 拿到组数据/group/a/jjj.jpg
            fullPath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), "jpg", null).getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回全路径 :  ip:port+xxxx
        return ResponseEntity.ok(serverHost + "/" + fullPath);
    }
}
